package com.ruoyi.ihome.service.impl;

import com.ruoyi.ihome.domain.Apartment;
import com.ruoyi.ihome.domain.ApartmentAndFacility;
import com.ruoyi.ihome.mapper.ApartmentAndFacilityMapper;
import com.ruoyi.ihome.mapper.ApartmentMapper;
import com.ruoyi.ihome.service.IApartmentService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import java.util.*;

import java.util.List;



/**
 * 公寓管理Service业务层处理
 *
 * @author zy
 * @date 2024-08-13
 */
@Service
public class ApartmentServiceImpl implements IApartmentService {
    @Resource
    private ApartmentMapper apartmentMapper;
    @Resource
    private ApartmentAndFacilityMapper apartmentAndFacilityMapper;

    /**
     * 查询公寓管理
     *
     * @param id 公寓管理主键
     * @return 公寓管理
     */
    @Override
    public Apartment selectApartmentById(Long id) {

        return apartmentMapper.selectApartmentById(id);
    }

    /**
     * 查询公寓管理列表
     *
     * @param apartment 公寓管理
     * @return 公寓管理
     */
    @Override
    public List<Apartment> selectApartmentList(Apartment apartment) {
//        List<Apartment> apartments = (List<Apartment>) redisTemplate.opsForValue().get("apartment");
//
//        if (apartments == null){
//            System.out.println("缓存中没有数据，查询数据库");
//            List<Apartment> list = apartmentMapper.selectApartmentList(apartment);
//           redisTemplate.opsForValue().set("apartment",list);
//           return list;
//        }
//        System.out.println("缓存中有数据，直接返回");

        List<Apartment> apartments = apartmentMapper.selectApartmentList(apartment);
        return apartments;
    }

    /**
     * 新增公寓管理
     *
     * @param apartment 公寓管理
     * @return 结果
     */
    @Override
    public int insertApartment(Apartment apartment) {

        long[] facilityIds = apartment.getFacilityIds();
        apartmentMapper.insertApartment(apartment);
        Long apartmentId = apartment.getId();
        int num = 0;
        for (long facilityId : facilityIds) {
            num = apartmentAndFacilityMapper.insertApartmentAndFacility(new ApartmentAndFacility(null, apartmentId, facilityId, 0));
        }
        return num;
    }

    /**
     * 修改公寓管理
     *
     * @param apartment 公寓管理
     * @return 结果
     */
    @Override
    public int updateApartment(Apartment apartment) {
        // 创建 ApartmentAndFacility 的实例，设置公寓 ID
        ApartmentAndFacility apartmentAndFacility = new ApartmentAndFacility();
        apartmentAndFacility.setApartmentId(apartment.getId());

        // 查询现有的设施记录
        List<ApartmentAndFacility> existingFacilities = apartmentAndFacilityMapper.selectApartmentAndFacilityList(apartmentAndFacility);

        // 获取新的设施 ID
        long[] newFacilityIds = apartment.getFacilityIds();

        // 检查是否有新的设施 ID
        if (newFacilityIds != null && newFacilityIds.length > 0) {
            // 如果有新的设施 ID，则先删除现有的设施记录
            if (!existingFacilities.isEmpty()) {
                Long[] facilityIdsToDelete = existingFacilities.stream()
                        .map(ApartmentAndFacility::getFacilityId)
                        .toArray(Long[]::new);
                apartmentAndFacilityMapper.deleteApartmentAndFacilityByIds(facilityIdsToDelete);
            }
            // 插入新的设施记录
            int totalInserted = 0;
            for (long facilityId : newFacilityIds) {
                totalInserted += apartmentAndFacilityMapper.insertApartmentAndFacility(new ApartmentAndFacility(null, apartment.getId(), facilityId, 0));
            }
            // 返回插入的设施记录总数
            return totalInserted;
        } else {
            return apartmentMapper.updateApartment(apartment);
        }
    }


    /**
     * 批量删除公寓管理
     *
     * @param ids 需要删除的公寓管理主键
     * @return 结果
     */
    @Override
    public int deleteApartmentByIds(Long[] ids) {
        int deleteIds = apartmentMapper.deleteApartmentByIds(ids);
        for (Long id : ids) {
            ApartmentAndFacility apartmentAndFacility = new ApartmentAndFacility();
            apartmentAndFacility.setApartmentId(id);
            List<ApartmentAndFacility> num = apartmentAndFacilityMapper.selectApartmentAndFacilityList(apartmentAndFacility);
            for (ApartmentAndFacility Facility : num) {
                apartmentAndFacilityMapper.deleteApartmentAndFacilityById(Facility.getId());
            }
        }
        return deleteIds;
    }

    @Override
    public List<Long> findApartmentsByFacilityIds(long facilityIds) {
        return findApartmentsByFacilityIds(facilityIds);
    }


    /**
     * 删除公寓管理信息
     *
     * @param id 公寓管理主键
     * @return 结果
     */
    @Override
    public int deleteApartmentById(Long id) {
        return apartmentMapper.deleteApartmentById(id);
    }

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public String position(String street, Double latitude, Double longitude) {
        Point point = new Point(longitude,latitude);
        Long add = redisTemplate.opsForGeo().add("locals",point,street);
        System.out.println(add);
        List<Point> local = redisTemplate.opsForGeo().position("locals", street);
        System.out.println(local);

        return "添加成功";
    }

    @Override
    public List<Object> selectLocal(String street, Double latitude, Double longitude) {
        Point point = new Point(longitude,latitude);
        Distance distance = new Distance(1000);
        Circle circle = new Circle(point, distance);
        GeoResults<RedisGeoCommands.GeoLocation<Object>> radius = redisTemplate.opsForGeo().radius("locals",circle);

        // 创建一个 List 来存储附近的房源信息
        List<Apartment> nearbyApartments = new ArrayList<>();
        if (radius != null) {
            for (GeoResult<RedisGeoCommands.GeoLocation<Object>> geoResult : radius) {
                // 获取地理位置对象
                RedisGeoCommands.GeoLocation<Object> geoLocation = geoResult.getContent();

                // 计算与目标位置的距离
                Distance distanceToTarget = redisTemplate.opsForGeo().distance("locals", geoLocation.getName(), point);

                // 查询数据库以获取详细的房源信息
                Apartment apartment = apartmentMapper.selectApartmentById(Long.valueOf(geoLocation.getName().toString()));

                // 添加到结果列表
                nearbyApartments.add(apartment);

                System.out.println("Distance to " + geoLocation.getName() + ": " + distanceToTarget);
                System.out.println("Apartment found: " + apartment);
            }
        }
        return Collections.singletonList(nearbyApartments);
    }


}
